<template>
  <div class="order-management">
    <div class="page-header">
      <h2>订单管理</h2>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in orderStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="list-card">
      <el-table
        v-loading="loading"
        :data="orderList"
        border
        style="width: 100%">
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getOrderStatusType(scope.row.status)">
              {{ getOrderStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100">
          <template slot-scope="scope">
            {{ getPaymentMethodText(scope.row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column label="下单时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="支付时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.updatedTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="250">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleDetail(scope.row)">详情</el-button>
            <el-button
              size="mini"
              type="success"
              v-if="scope.row.status === 'PAID'"
              @click="handleShip(scope.row)">发货</el-button>
            <el-button
              size="mini"
              type="danger"
              v-if="scope.row.status === 'PENDING'"
              @click="handleCancel(scope.row)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="detailDialogVisible" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ currentOrder.username }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ currentOrder.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getOrderStatusType(currentOrder.status)">
            {{ getOrderStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">
          {{ getPaymentMethodText(currentOrder.paymentMethod) }}
        </el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ formatDateTime(currentOrder.createdTime) }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ formatDateTime(currentOrder.updatedTime) }}</el-descriptions-item>
        <el-descriptions-item label="收货人">{{ currentOrder.receiverName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentOrder.receiverPhone }}</el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.receiverAddress }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentOrder.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <div class="order-items" style="margin-top: 20px;">
        <h3>订单商品</h3>
        <el-table :data="currentOrder.orderItems || []" border>
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="price" label="单价" width="120">
            <template slot-scope="scope">
              ¥{{ scope.row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column label="小计" width="120">
            <template slot-scope="scope">
              ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderList, updateOrderStatus, getOrderDetail } from '@/api/admin'
import { formatDateTime } from '@/utils/date'

export default {
  name: 'OrderManagement',
  
  data() {
    return {
      loading: false,
      orderList: [],
      searchForm: {
        orderNo: '',
        username: '',
        status: '',
        dateRange: []
      },
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      detailDialogVisible: false,
      currentOrder: {},
      orderStatusOptions: [
        { value: 'PENDING', label: '待付款' },
        { value: 'PAID', label: '已付款' },
        { value: 'SHIPPED', label: '已发货' },
        { value: 'COMPLETED', label: '已完成' },
        { value: 'CANCELLED', label: '已取消' }
      ]
    }
  },

  created() {
    this.fetchData()
  },

  methods: {
    formatDateTime,

    getOrderStatusType(status) {
      const statusMap = {
        pending: 'warning',
        paid: 'success',
        shipped: 'primary',
        completed: 'success',
        cancelled: 'danger'
      }
      return statusMap[status] || 'info'
    },

    getOrderStatusText(status) {
      const statusMap = {
        pending: '待付款',
        paid: '已付款',
        shipped: '已发货',
        completed: '已完成',
        cancelled: '已取消'
      }
      return statusMap[status] || status
    },

    getPaymentMethodText(method) {
      const methodMap = {
        alipay: '支付宝',
        wechat: '微信支付',
        creditCard: '信用卡'
      }
      return methodMap[method] || method
    },

    async fetchData() {
      this.loading = true
      try {
        const params = {
          pageNum: this.page.pageNum,
          pageSize: this.page.pageSize,
          ...this.searchForm,
          startDate: this.searchForm.dateRange?.[0],
          endDate: this.searchForm.dateRange?.[1]
        }
        delete params.dateRange
        const { data } = await getOrderList(params)
        this.orderList = data.list
        this.page.total = data.total
      } catch (error) {
        console.error('获取订单列表失败:', error)
        this.$message.error('获取订单列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.page.pageNum = 1
      this.fetchData()
    },

    resetSearch() {
      this.searchForm = {
        orderNo: '',
        username: '',
        status: '',
        dateRange: []
      }
      this.handleSearch()
    },

    handleSizeChange(val) {
      this.page.pageSize = val
      this.fetchData()
    },

    handleCurrentChange(val) {
      this.page.pageNum = val
      this.fetchData()
    },

    handleDetail(row) {
      this.currentOrder = { ...row };
      
      // 获取详细订单信息，包括商品详情
      this.loading = true;
      const { id } = row;
      
      getOrderDetail(id).then(response => {
        if (response.code === 200 && response.data) {
          this.currentOrder = response.data;
          console.log('订单详情:', this.currentOrder);
        }
      }).catch(error => {
        console.error('获取订单详情失败:', error);
        this.$message.error('获取订单详情失败');
      }).finally(() => {
        this.loading = false;
        this.detailDialogVisible = true;
      });
    },

    async handleShip(row) {
      try {
        await this.$confirm('确认发货吗？', '提示', {
          type: 'warning'
        })
        await updateOrderStatus(row.id, 'SHIPPED')
        this.$message.success('发货成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('发货失败:', error)
          this.$message.error('发货失败')
        }
      }
    },

    async handleCancel(row) {
      try {
        await this.$confirm('确认取消该订单吗？', '提示', {
          type: 'warning'
        })
        await updateOrderStatus(row.id, 'CANCELLED')
        this.$message.success('取消订单成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消订单失败:', error)
          this.$message.error('取消订单失败')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.order-management {
  padding: 20px;

  .page-header {
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .list-card {
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style> 